Published on

How to create custom view modifiers in SwiftUI

Authors
  • Name
    Twitter

How to create a custom ViewModifier

To create a custom view modifier, we define a struct that conforms to the ViewModifier protocol.

In this case, we will create a ::PinkLabel:: modifier, which turns the text's color into pink.

struct PinkLabel: ViewModifier {
    func bode(content: Content) -> some View {
        // ....
    }
}

ViewModifier protocol has only one requiremented method, body(). We return modified version of our content from this method.

public protocol ViewModifier {
    @ViewBuilder @MainActor func body(content: Self.Content) -> Self.Body
}

For our PinkLabel modifier, we just need to set the .foregroundStyle to Color.pink.

struct PinkLabel: ViewModifier {
    func body(content: Content) -> some View {
        content.
            foregroundStyle(Color.pink)
    }
}

That's all we need to do to create a custom view modifier